# -*- coding: utf-8 -*-
# @Author	: changfeng
# @Date		: 2025/9/12 15:32
# @Last Modified by:   changfeng
# @Last Modified time: 2025/9/12 15:32
# Thanks for your comments!
import logging
import traceback

from src.basedata.application import commands
from src.basedata.domain.service.basedata_sync import BaseDataSync
from src.basedata.infrastructure.common.unit_of_work import AbstractUnitOfWork
from src.seedwork.application import responses

logger = logging.getLogger(__name__)


async def sync_app_department_data(
        cmd: commands.SyncAppDepartments,
        uow: AbstractUnitOfWork,
):
    success_resp = responses.SuccessResponse()
    async with uow:
        try:
            collection_message = []
            data_sync_obj = BaseDataSync(uow)
            await data_sync_obj.sync_basedata_from_his(app_id=cmd.app_id, method_name="department",
                                                       collection_message=collection_message)
            if len(collection_message) > 0:
                resp = responses.SyncDepartmentFailResponse()
                resp.details = collection_message
                return resp
        except Exception as e:
            logger.error(traceback.format_exc())
            return responses.ExceptionResponse(str(e))
    return success_resp


async def sync_app_person_data(
        cmd: commands.SyncAppPersons,
        uow: AbstractUnitOfWork,
):
    success_resp = responses.SuccessResponse()
    async with uow:
        try:
            collection_message = []
            data_sync_obj = BaseDataSync(uow)
            await data_sync_obj.sync_basedata_from_his(app_id=cmd.app_id, method_name="users",
                                                       collection_message=collection_message)
            if len(collection_message) > 0:
                resp = responses.SyncPersonFailResponse()
                resp.details = collection_message
                return resp
        except Exception as e:
            logger.error(traceback.format_exc())
            return responses.ExceptionResponse(str(e))
    return success_resp


async def sync_app_medicines_data(
        cmd: commands.SyncAppMedicines,
        uow: AbstractUnitOfWork,
):
    success_resp = responses.SuccessResponse()
    async with uow:
        try:
            collection_message = []
            data_sync_obj = BaseDataSync(uow)
            await data_sync_obj.sync_basedata_from_his(app_id=cmd.app_id, method_name="medicine",
                                                       collection_message=collection_message)
            if len(collection_message) > 0:
                resp = responses.SyncMedicineFailResponse()
                resp.details = collection_message
                return resp
        except Exception as e:
            logger.error(traceback.format_exc())
            return responses.ExceptionResponse(str(e))
    return success_resp


async def sync_app_route_of_administration_data(
        cmd: commands.SyncAppRouteOfAdministration,
        uow: AbstractUnitOfWork,
):
    success_resp = responses.SuccessResponse()
    async with uow:
        try:
            collection_message = []
            data_sync_obj = BaseDataSync(uow)
            await data_sync_obj.sync_basedata_from_his(app_id=cmd.app_id, method_name="route",
                                                       collection_message=collection_message)
            if len(collection_message) > 0:
                resp = responses.SyncAdministratorRouteFailResponse()
                resp.details = collection_message
                return resp
        except Exception as e:
            logger.error(traceback.format_exc())
            return responses.ExceptionResponse(str(e))
    return success_resp


async def sync_app_administration_freq_data(
        cmd: commands.SyncAppAdministrationFreq,
        uow: AbstractUnitOfWork,
):
    success_resp = responses.SuccessResponse()
    async with uow:
        try:
            collection_message = []
            data_sync_obj = BaseDataSync(uow)
            await data_sync_obj.sync_basedata_from_his(app_id=cmd.app_id, method_name="freq",
                                                       collection_message=collection_message)
            if len(collection_message) > 0:
                resp = responses.SyncFreqFailResponse()
                resp.details = collection_message
                return resp
        except Exception as e:
            logger.error(traceback.format_exc())
            return responses.ExceptionResponse(str(e))
    return success_resp


async def sync_disease_code_data(
        cmd: commands.SyncAppDiseaseCode,
        uow: AbstractUnitOfWork,
):
    success_resp = responses.SuccessResponse()
    async with uow:
        try:
            collection_message = []
            data_sync_obj = BaseDataSync(uow)
            await data_sync_obj.sync_basedata_from_his(app_id=cmd.app_id, method_name="disease",
                                                       collection_message=collection_message)
            if len(collection_message) > 0:
                resp = responses.SyncDiseaseCodeFailResponse()
                resp.details = collection_message
                return resp
        except Exception as e:
            logger.error(traceback.format_exc())
            return responses.ExceptionResponse(str(e))
    return success_resp


async def query_app_department_data(
        cmd: commands.QueryAppDepartments,
        uow: AbstractUnitOfWork,
):
    success_resp = responses.SuccessResponse()
    async with uow:
        try:
            app_config = await uow.app_config.get_basedata_sync_config(cmd.app_id)
            if not app_config:
                return responses.UnFoundAppConfigResponse("机构基础数据配置为查到")
            data_sync_obj = BaseDataSync(uow)
            result, data = await data_sync_obj.get_data_from_his(app_config[0], "/basedata/getdeptlist", "department")
            if result is True:
                result = []
                for d in data:  # 先临时这样处理吧，后面改成DTO转换吧
                    item = d.dict()
                    item['Category'] = item['Category'].value
                    result.append(item)
                success_resp.data = result
            else:
                return responses.GetDataFailResponse(data)
        except Exception as e:
            logger.error(traceback.format_exc())
            return responses.ExceptionResponse(str(e))
    return success_resp


async def query_app_person_data(
        cmd: commands.QueryAppPersons,
        uow: AbstractUnitOfWork,
):
    success_resp = responses.SuccessResponse()
    async with uow:
        try:
            app_config = await uow.app_config.get_basedata_sync_config(cmd.app_id)
            if not app_config:
                return responses.UnFoundAppConfigResponse("机构基础数据配置为查到")
            data_sync_obj = BaseDataSync(uow)
            result, data = await data_sync_obj.get_data_from_his(app_config[0], "/basedata/getuserlist", "person")
            if result is True:
                # Type: PersonType  # 员工类别
                #     Gender: PersonGender
                result = []
                for d in data:  # 先临时这样处理吧，后面改成DTO转换吧
                    item = d.dict()
                    item['Type'] = item['Type'].value
                    item['Gender'] = item['Gender'].value
                    result.append(item)
                success_resp.data = result
            else:
                return responses.GetDataFailResponse(data)
        except Exception as e:
            logger.error(traceback.format_exc())
            return responses.ExceptionResponse(str(e))
    return success_resp


async def query_app_medicines_data(
        cmd: commands.QueryAppMedicines,
        uow: AbstractUnitOfWork,
):
    success_resp = responses.SuccessResponse()
    async with uow:
        try:
            app_config = await uow.app_config.get_basedata_sync_config(cmd.app_id)
            if not app_config:
                return responses.UnFoundAppConfigResponse("机构基础数据配置为查到")
            data_sync_obj = BaseDataSync(uow)
            result, data = await data_sync_obj.get_data_from_his(app_config[0], "/basedata/getmedicinelist", "medicine")
            if result is True:
                # CNWestFlag: MedicineCNWestFlag  # 中西药标识
                #     AntibacType: Med
                result = []
                for d in data:  # 先临时这样处理吧，后面改成DTO转换吧
                    item = d.dict()
                    item['CNWestFlag'] = item['CNWestFlag'].value
                    item['AntibacType'] = item['AntibacType'].value
                    result.append(item)
                success_resp.data = result
            else:
                return responses.GetDataFailResponse(data)
        except Exception as e:
            logger.error(traceback.format_exc())
            return responses.ExceptionResponse(str(e))
    return success_resp


async def query_app_route_of_administration_data(
        cmd: commands.QueryAppRouteOfAdministration,
        uow: AbstractUnitOfWork,
):
    success_resp = responses.SuccessResponse()
    async with uow:
        try:
            app_config = await uow.app_config.get_basedata_sync_config(cmd.app_id)
            if not app_config:
                return responses.UnFoundAppConfigResponse("机构基础数据配置为查到")
            data_sync_obj = BaseDataSync(uow)
            result, data = await data_sync_obj.get_data_from_his(app_config[0], "/basedata/getadminroutlist",
                                                                 "administration")
            if result is True:
                success_resp.data = [d.dict() for d in data]
            else:
                return responses.GetDataFailResponse(data)
        except Exception as e:
            logger.error(traceback.format_exc())
            return responses.ExceptionResponse(str(e))
    return success_resp


async def query_app_administration_freq_data(
        cmd: commands.QueryAppAdministrationFreq,
        uow: AbstractUnitOfWork,
):
    success_resp = responses.SuccessResponse()
    async with uow:
        try:
            app_config = await uow.app_config.get_basedata_sync_config(cmd.app_id)
            if not app_config:
                return responses.UnFoundAppConfigResponse("机构基础数据配置为查到")
            data_sync_obj = BaseDataSync(uow)
            result, data = await data_sync_obj.get_data_from_his(app_config[0], "/basedata/getadminfreqlist", "freq")
            if result is True:
                success_resp.data = [d.dict() for d in data]
            else:
                return responses.GetDataFailResponse(data)
        except Exception as e:
            logger.error(traceback.format_exc())
            return responses.ExceptionResponse(str(e))
    return success_resp


async def query_app_disease_code_data(
        cmd: commands.QueryAppDiseaseCode,
        uow: AbstractUnitOfWork,
):
    success_resp = responses.SuccessResponse()
    async with uow:
        try:
            app_config = await uow.app_config.get_basedata_sync_config(cmd.app_id)
            if not app_config:
                return responses.UnFoundAppConfigResponse("机构基础数据配置为查到")
            data_sync_obj = BaseDataSync(uow)
            result, data = await data_sync_obj.get_data_from_his(app_config[0], "/basedata/getdiseaselist", "icd")
            if result is True:
                success_resp.data = [d.dict() for d in data]
            else:
                return responses.GetDataFailResponse(data)
        except Exception as e:
            logger.error(traceback.format_exc())
            return responses.ExceptionResponse(str(e))
    return success_resp


async def update_person_cache(
        cmd: commands.UpdatePersonCache,
        uow: AbstractUnitOfWork
):
    success_resp = responses.SuccessResponse()
    async with uow:

        for app_code, data in cmd.data.items():
            try:
                await uow.person.save_data_to_redis(app_code, data)
            except Exception as e:
                logger.error(f"update person cache failed {traceback.format_exc()}")
    return success_resp
